<template>
  <view class="chat-page">

    <view style="margin-bottom: 30px">当前聊天用户：{{ currentUser.name }}</view>
    <view v-for="message in currentUser.messageList" :key="message.id" class="message-item">

      <view v-if="message.sender === currentUser.name" class="my-message">
        <image :src="currentUser.avatar" class="avatar"/>
        <view class="content">
          <text>{{ message.body }}</text>
        </view>
      </view>
      <view v-else class="other-message">
        <image :src="message.avatar" class="avatar"/>
        <view class="content">
          <text class="sender">{{ message.sender.name }}</text>
          <text>{{ message.body }}</text>
        </view>
      </view>
    </view>
    <view class="input-bar">
      <input v-model="inputMessage" type="text" placeholder="请输入消息" class="input-box"/>
      <button @click="sendMessage" class="send-btn">发送</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      //咨询的学生
      currentUser: {},

      inputMessage: ''
    };
  },
  onLoad(options) {
    // 从URL参数获取聊天用户的ID，并根据ID获取用户信息
    let name = options.user;
    this.$store.state.chat.onlineUser.forEach(o=>{
      if (o.name===name){
        this.currentUser =o;
      }
    })


  },

  methods: {
    getUserById(userId) {
      // 根据用户ID获取用户信息的逻辑
      // 返回用户对象
      return {name: userId, avatar: "http://p2.ssl.qhimg.com/dm/72_72_100/t01153c5aa2c2a26d26.png"}
    },
    sendMessage() {
      const newMessage = {
        body: this.inputMessage, sender: "马老师",
        avatar: "http://36.111.170.197:9000/profile/upload/2023/09/03/OIP-C_20230903091522A001.jpg",
        target: this.currentUser.name,
        type: "MESSAGE"
      };
      uni.sendSocketMessage({
        data: JSON.stringify(newMessage)
      });
      this.inputMessage = '';
    }
  }
};
</script>

<style>
.chat-page {
  padding: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.message-item {
  margin-bottom: 10px;

  align-items: center;
}

.my-message {
  flex-direction: row-reverse;
}

.other-message {
  text-align: right;
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.content {
  background-color: #e5e5ea;
  padding: 10px;
  border-radius: 10px;
  display: inline;
}

.sender {
  font-size: 12px;
  margin-bottom: 5px;
}

.input-bar {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.input-box {
  flex: 1;
  height: 40px;
  border: 1px solid #e5e5ea;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
}

.send-btn {
  background-color: #1aad19;
  color: #ffffff;
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 14px;
  margin-left: 10px;
}
</style>